<template>
  <div class="shake-animation">
    <div class="user" :class="{ 'apply-shake': flag }" @click="shake('flag')">点我就会抖动</div>
    <br />
    <br />
    <br />
    <el-form :model="formData" :rules="rules">
      <el-form-item :class="{ 'apply-shake': formFlag }" label="失焦后为空则抖动提示" prop="keyword">
        <el-input v-model.trim="formData.keyword"></el-input>
      </el-form-item>
    </el-form>
    <br />
    <br />
    <br />
    <h1>v-rap</h1>
    <transition enter-active-class="apply-shake" leave-active-class="go">
      <input type="text" ref="input" v-model="keyword" :key="keyword" @input="han">
    </transition>
  </div>
</template>

<script>
export default {
  name: "shakeAnimation",
  data() {
    return {
      flag: false,
      formFlag: false,
      formData: {
        keyword: ''
      },
      rules: {
        keyword: [{ required: true, validator: this.checkKeyword, trigger: 'blur', shake: true }]
      },
      keyword: ''
    }
  },
  methods: {
    shake(d) {
      this[d] = true
      setTimeout(() => {
        this[d] = false
      }, 900)
    },
    checkKeyword(rule, value, callback) {
      if (!value) {
        this.shake('formFlag')
        return callback(new Error('不能为空'))
      } else {
        return callback()
      }
    },
    han($event) {
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    }
  }
}
</script>

<style scoped>
@keyframes shake {

  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }

  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

.apply-shake {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both;
  pointer-events: none;
}

.user {
  user-select: none;
}

.shake-animation {
  padding: 50px;
}

.go {
  display: none;
}
</style>
